package com.atguigu.gulimall.cart.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.CartConstat;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 2022/4/18 21:26 星期一
 * CartInterceptor
 * 拦截器
 * 作用： 在执行目标方法之前，判断用户的登录状态并封装传递给controller目标请求
 * Created by ASIA 乔帅阳 .
 * --
 * --
 */

//@Component   //组件的意思  Component往spring容器中放组件
public class CartInterceptor implements HandlerInterceptor {

    //ThreadLocal同一个线程共享数据
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    //在目标方法之前拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

        UserInfoTo userInfoVo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberRespVo memberResponseVo = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(memberResponseVo != null){
            userInfoVo.setUserId(memberResponseVo.getId());
        }
        Cookie[] cookies = request.getCookies();
        if(cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies){
                String name = cookie.getName();
                if(name.equals(CartConstat.TEMP_USER_COOKIE_NAME)){
                    userInfoVo.setUserKey(cookie.getValue());
                    userInfoVo.setTempUser(true);
                }
            }
        }
       //如果没有临时用户用户一定分配一个临时用户
        if(StringUtils.isEmpty(userInfoVo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfoVo.setUserKey(uuid);
        }
        threadLocal.set(userInfoVo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
      UserInfoTo userInfoTo = threadLocal.get();
        if(!userInfoTo.isTempUser()){
        //持续的延长用户过期时间
        Cookie cookie = new Cookie(CartConstat.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
        cookie.setDomain("qsy.sale");//作用于
        cookie.setMaxAge(CartConstat.TEMP_USER_COOKIE_TIMEOUT);//最大时间
        response.addCookie(cookie);
    }
    }
}
